package com.sskj.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.Address;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.allen.library.SuperTextView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.AppDirectCheckUtil;
import com.sskj.lib.util.AppOuterCheckUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.CopyUtil;
import com.sskj.lib.util.HideUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.lib.util.TipUtil;
import com.sskj.mine.account.AccountManagerActivity;
import com.sskj.mine.asset.AddressListActivity;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.dialog.TipDialog;
import com.sskj.mine.invite.InviteActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/05/01
 */
@Route(path = RConfig.MINE_FRAGMENT_MAIN)
public class MineFragment extends BaseFragment<MinePresenter> {

    @BindView(R2.id.user_head_img)
    ImageView userHeadImg;
    @BindView(R2.id.mine_setting)
    ImageView mineSetting;
    @BindView(R2.id.name_tv)
    TextView nameTv;

    @BindView(R2.id.usdt_num)
    TextView usdtNum;
    @BindView(R2.id.account_cny)
    TextView accountCny;

    @BindView(R2.id.account_num)
    TextView accountNum;
    @BindView(R2.id.lc_cny)
    TextView lcCny;

    @BindView(R2.id.user_slogan)
    TextView userSlogan;
    @BindView(R2.id.user_id)
    TextView userId;
    @BindView(R2.id.uid_tv)
    TextView uid_tv;
    @BindView(R2.id.menu_person)
    SuperTextView menuPerson;
    @BindView(R2.id.menu_security)
    SuperTextView menuSecurity;
    @BindView(R2.id.menu_address)
    SuperTextView menuAddress;
    @BindView(R2.id.menu_chujin)
    SuperTextView menu_chujin;
    @BindView(R2.id.menu_rujin)
    SuperTextView menu_rujin;
    @BindView(R2.id.menu_zcgl)
    SuperTextView menuZcgl;
    @BindView(R2.id.menu_invite)
    SuperTextView menuInvite;
    @BindView(R2.id.menu_finance)
    SuperTextView menuFinance;
    @BindView(R2.id.menu_borrow)
    SuperTextView menuBorrow;
    @BindView(R2.id.menu_about_us)
    SuperTextView menuAboutUs;
    @BindView(R2.id.logout_btn)
    Button logoutBtn;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R2.id.llFinanceAccount)
    LinearLayout llFinanceAccount;
    @BindView(R2.id.llTradeAccount)
    LinearLayout llTradeAccount;
    @BindView(R2.id.mine_gonggao)
    SuperTextView mineGg;  // 公告
    @BindView(R2.id.tvUsdt)
    TextView tvUsdt;
    @BindView(R2.id.tvMyr)
    TextView tvMyr;
    @BindView(R2.id.ll_user_name)
    LinearLayout ll_user_name;
    private String imgFirst;
    private UserData mUserData;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private boolean isOut;

    @Override
    public int getLayoutId() {
        return R.layout.mine_fragment_mine;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                mPresenter.requestUserInfo();
            }
        });
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                updateUserTitle(userData);
            } else {
                userData = null;
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    protected void initEvent() {
        // 设置
        ClickUtil.click(mineSetting, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {  // 登录
                return;
            }
            SettingActivity.start(getContext());
        });
        // 提币地址
        ClickUtil.click(menuAddress, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            AddressListActivity.start(getContext());
        });
        //资产管理
        ClickUtil.click(menuZcgl, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.ASSET_MANAGE).navigation();
        });

        //出金
        ClickUtil.click(menu_chujin, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            isOut = true;
            mPresenter.requsetPayWayList();

        });

        //入金
        ClickUtil.click(menu_rujin, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
//            if (!AppDirectCheckUtil.checkPayType(getActivity(),mUserData)){
//                return;
//            }
            isOut = false;
            mPresenter.requsetPayWayList();
        });

        // 公告
        ClickUtil.click(mineGg, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.APP_GONGGAO_LIST).navigation();
        });
//        // 设置头像
//        ClickUtil.click(userHeadImg, () -> {
//            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
//                return;
//            }
//            selectImage(1);
//        });
        //个人中心
        ClickUtil.click(menuPerson, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            PersonActivity.start(getContext());
        });
        //安全中心
        ClickUtil.click(menuSecurity, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            SecurityActivity.start(getContext());
        });
        //我要理财
        ClickUtil.click(menuFinance, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            if (!AppCircleCheckUtil.checkAuth(getActivity(), userData)) {
                return;
            }
            if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.FINAN_I_WANT_FINANCE).navigation();
        });
        //抵押借款
        ClickUtil.click(menuBorrow, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            if (!AppCircleCheckUtil.checkAuth(getActivity(), userData)) {
                return;
            }
            if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.FINAN_DYJK).navigation();

        });
        //邀请返佣
        ClickUtil.click(menuInvite, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            InviteActivity.start(getContext());
        });
        //关于我们
        ClickUtil.click(menuAboutUs, () -> {
            mPresenter.getContract();
        });

        //退出登录
        ClickUtil.click(logoutBtn, () -> {
            TipUtil.getSureCancelTip(getActivity(), App.INSTANCE.getString(R.string.mine_mineFragment1_j), App.INSTANCE.getString(R.string.mine_mineFragment2_j), App.INSTANCE.getString(R.string.mine_activity_buy85_j0), () -> {
                LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
                logoutProvider.logout();
            });
        });

        //个人中心
        ClickUtil.click(userHeadImg, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            PersonActivity.start(getContext());
        });
        ClickUtil.click(ll_user_name, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            PersonActivity.start(getContext());
        });
    }


    public void updateUserTitle(UserData userData) {
        mUserData = userData;
//        ImageUtil.setCircleImage(TextUtils.isEmpty(userData.getUpic()) ? getResources().getDrawable(R.mipmap.mine_user_head) : userData.getUpic(), userHeadImg);
        nameTv.setText(SPUtil.get(SPConfig.USER_ACCOUNT, "").contains("@") ? HideUtil.getEmialAddress(SPUtil.get(SPConfig.USER_ACCOUNT, "")) : HideUtil.getPhoneHide(SPUtil.get(SPConfig.USER_ACCOUNT, "")));
        uid_tv.setText("UID: " + userData.getUid());

        usdtNum.setText(CoinUtil.keepUSDT(userData.getZc_total().getTtl_money()));
        accountNum.setText(CoinUtil.keepUSDT(userData.getLc_total().getTtl_money1()));

        accountCny.setText("≈" + CoinUtil.keepRMB(userData.getZc_total().getTtl_cnymoney()) + Constans.DANWEI);
        lcCny.setText("≈" + CoinUtil.keepRMB(userData.getLc_total().getTtl_cnymoney1()) + Constans.DANWEI);

        tvUsdt.setText("≈" + CoinUtil.keepUSDT(userData.getZc_total().getTtl_money()));
        tvMyr.setText(userData.getZc_total().getTtl_twdmoney());

        userSlogan.setText(userData.getGrade());
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
        ClickUtil.click(llFinanceAccount, () -> {
            ARouter.getInstance().build(RConfig.FINAN_TRADE_ACCOUNT)
                    .withBoolean(Constans.IS_TRADE, false)
                    .navigation();
        });
        ClickUtil.click(llTradeAccount, () -> {
            ARouter.getInstance().build(RConfig.FINAN_TRADE_ACCOUNT)
                    .withBoolean(Constans.IS_TRADE, true)
                    .navigation();
        });
    }

    public void uploadFail() {
        Glide.with(this).load(getResources().getDrawable(R.mipmap.mine_user_head)).into(userHeadImg);
    }

    public void putList(String url) {
        imgFirst = url;
    }

    @SuppressLint("CheckResult")
    private void selectImage(int requestCode) {
        new RxPermissions(getActivity())
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())
                                .previewImage(true)
                                .isCamera(true)
                                .imageFormat(PictureMimeType.JPEG)
                                .maxSelectNum(1)
                                .compress(true)
                                .forResult(requestCode);
                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onResultPicture(Intent data) {
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
        if (selectList != null && selectList.size() > 0) {
            LocalMedia media = selectList.get(0);
            String url;
            if (media.isCompressed()) {
                url = media.getCompressPath();
            } else {
                url = media.getPath();
            }
            ImageUtil.setCircleImage(url, userHeadImg);
            mPresenter.submitVerify(new File(url));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
//        mPresenter.requestUserInfo();
        userViewModel.update();
        if (userViewModel != null) {
            userViewModel.update();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (userViewModel != null) {
                userViewModel.update();
            }
        }
    }

    public void cancelShopSuccess() {
        if (userViewModel != null) {
            userViewModel.update();
        }
    }

    public void showEmail(String email) {
        TipUtil.getSureCancelTip(getActivity(), App.INSTANCE.getString(R.string.mine_settingPasswordActivity1_j), email, App.INSTANCE.getString(R.string.mine_mineFragment5_j), () -> {
            CopyUtil.copy(email);
        });
    }

    public void onPayTypeSuccess() {
        if (isOut) {

            ShellActivity.start(getContext());
        } else {
            if (!AppCircleCheckUtil.checkHighAuth(getActivity(), userData)) {
                return;
            }
            Intent intent = new Intent(getActivity(), BuyActivity.class);
            intent.putExtra("isOffline", true);
            startActivity(intent);
        }

    }

    public void onPayTypeFail() {
        AppDirectCheckUtil.checkPayType(getActivity(), false);

    }
}
